﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using SqlsugarService.Application.Until;
using SqlsugarService.Domain;
using SqlsugarService.Infrastructure.DbContext;
using SqlsugarService.Application.IService;
using SqlsugarService.Infrastructure.IRepository;

namespace SqlsugarService.Application.Service
{
    public class UserService: IUserService
    {
        private readonly SqlSugarDbContext _dbContext;
        private readonly IBaseRepository<Users> baseRepository;

        public UserService(SqlSugarDbContext dbContext, IBaseRepository<Users> baseRepository)
        {
            _dbContext = dbContext;
            this.baseRepository = baseRepository;
        }

        public async Task<ApiResult<List<Users>>> GetUsers()
        {
            var res=await baseRepository.GetAllAsync();
            

            return ApiResult<List<Users>>.Success(res, ResultCode.Success);
        }
        public async Task<ApiResult<PageResult<List<Users>>>> GetUserspage(Seach seach)
        {
            var res = await baseRepository.GetAllAsync();
            var totalCount=res.Count;
            var totalPage=(int)Math.Ceiling(totalCount*1.0 / seach.PageSize);
            res =res.OrderBy(x=>x.Id).Skip((seach.PageIndex - 1) * seach.PageSize).Take(seach.PageSize).ToList();
           

            return ApiResult<PageResult<List<Users>>>.Success(new PageResult<List<Users>>() { TotalCount=totalCount,TotalPage=totalPage,Data=res}, ResultCode.Success);
        }
        public async Task<ApiResult> AddUser(Users user)
        {
            // 你可以在这里做一些校验，比如用户名/邮箱唯一性等
            var count = _dbContext.Db.Queryable<Users>().Count(u => u.Username == user.Username || u.Email == user.Email);
            user.Id = Guid.NewGuid();
            user.CreatedBy = "admin";
            if (count > 0)
            {
                // 已存在同名或同邮箱用户
                return ApiResult.Fail("用户名或邮箱已存在", ResultCode.NotFound);
            }
            // 插入用户
            var result = _dbContext.Db.Insertable(user).ExecuteCommand();
            return ApiResult.Success(ResultCode.Success);
        }
    }
}
